//
//  StatusListViewModel.m
//  王雷Sinoweibo
//
//  Created by wanglei on 16/11/29.
//  Copyright © 2016年 wanglei. All rights reserved.
//


#import "StatusListViewModel.h"
static StatusListViewModel *statusListViewModel = nil;
typedef void(^isSuccess)(BOOL isSuccess);

@implementation StatusListViewModel

+(instancetype)sharedAccountModel;{
    static dispatch_once_t oncetoken;
    dispatch_once(&oncetoken, ^{
        statusListViewModel = [[StatusListViewModel alloc]init];
    });
    return statusListViewModel;
}

- (void)loadHomeDate:(BOOL)isPullUp finished:(success)isSuccess{
//    NSString *urlstr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    NSString *urlstr = @"2/statuses/home_timeline.json";
    //    拼接字符串
    //    https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00n7IerCd4eGIB244a205d7djNvOxC
    NSString *token = [AccountViewModel sharedAccountModel].access_token;
    NSLog(@"----%@-----",token);
    if (token == nil) {
        [SVProgressHUD showErrorWithStatus:@"请先登录"];
        return ;
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:token forKey:@"access_token"];
    self.parameters = dict;
    NSLog(@"self.parameters = %@",self.parameters);
    if (isPullUp) {
        NSLog(@"self.homeArray = %@",self.homeArray);
        self.max_id =  (self.homeArray.lastObject.id != NULL) ? self.homeArray.lastObject.id : 0 ;
        NSLog(@"_max_id = %@",_max_id);
    }else{
        self.since_Id = (self.homeArray.firstObject.id != NULL) ? self.homeArray.firstObject.id : 0 ;
    }
    
    if (_max_id > 0) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:token forKey:@"access_token"];
        NSNumber *Max = [[NSNumber alloc]initWithDouble:([self.max_id doubleValue] - 1.0)];
       /*这是使用intValue的打印结果,
        self.max_id = 4048288376069262,Max = -1768252275
        这是使用floatValue的打印结果,
        self.max_id = 4048288376069262,Max = 4.048288e+15
       这是使用doubleValue的打印结果
        self.max_id = 4048288376069262,Max = 4048288376069261
        因此不同类型在转换的时候,一定要确保精度
        */
        NSLog(@"self.max_id = %@,Max = %@",self.max_id,Max);
//解决了有两条数据重复的bug
         NSMutableDictionary *Dict = [NSMutableDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",Max] forKey:@"max_id"];
        [dict addEntriesFromDictionary:Dict];
        self.parameters = dict;
        NSLog(@"self.parameters = %@",self.parameters);
    }
    if (_since_Id > 0) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:token forKey:@"access_token"];
        NSDictionary *Dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",self.since_Id] forKey:@"since_id"];
        //        一定要理解一个字典中是可以有多个键值对的,addEntriesFromDictionary的作用是将Dict中的键值对添加到dict的键值对后面,这个方法是没有返回值得,就是将已经存在的字典后面有增加了一部分内容   http://blog.csdn.net/yi_zz32/article/details/52484061
        [dict addEntriesFromDictionary:Dict];
        self.parameters = dict;
        NSLog(@"self.parameters = %@",self.parameters);
    }
    
    //    开始转动小菊花
    
    [[HTTPClient sharedClient] requestJSONDict:GET urlstring:urlstr parameters:_parameters finished:^(NSDictionary *dict, NSError *error) {
        if(error != nil){
            isSuccess(false);
            return ;
        }
        NSArray *array = dict[@"statuses"];
        if (![array isKindOfClass:[NSArray class]]) {
            [SVProgressHUD showErrorWithStatus:@"array数据类型不匹配,解析错误"];
            isSuccess(false);
            return ;
        }
        NSMutableArray *mutarray = [[NSMutableArray alloc]init];
        //        字典转模型
        for (NSDictionary *dict in array) {
            Status *status = [Status StatuesWithDict:dict];
            //            NSLog(@"%@",dict[@"user"]);
            [mutarray addObject:status];
        }
        if (self.since_Id > 0) {
            //            注意arrayByAddingObjectsFromArray是把self.homeArray里面的值加在了mutarray的值得后面,因此mutarray 和 self.homeArray的位置不能随便互换,互换后得到的数组里面元素的排序是不一样的
            self.homeArray = [mutarray arrayByAddingObjectsFromArray:self.homeArray];
        }else
            if(self.max_id > 0){
                //            这里很重要,牵涉到self.homeArray里面的数组的排序,这里表示将mutarray加到self.homeArray的后面
                self.homeArray = [self.homeArray arrayByAddingObjectsFromArray:mutarray];
                //            [_indicatorView stopAnimating];
            }
            else{
                //            首次加载数据
                self.homeArray = mutarray;
            }
        //将单张图片下载到本地 之后 才能够回调
        [self cacheStatusImage:mutarray isSuccess:isSuccess];
        isSuccess(true);
        //        从这里才开始执行tableview的代理方法的
        NSLog(@"-self.homeArray---%@----",self.homeArray);
    }];
}

- (void)cacheStatusImage:(NSArray <Status *>*)array isSuccess:(success)isSuccess{
    
    if (array.count == 0) {
        return;
    }
    // '群组队列'监听一组异步组任务完成得到统一回调
    //面临的问题 是多次的异步任务执行 需要得到统一的完成回调
 
    dispatch_group_t group = dispatch_group_create();
    
    for (Status *s in array) {
        int imageCount = s.pictureURLs.count;
        if(imageCount == 1){
            //在将要开始异步任务前面 向群组中添加异步任务 任务池的任务 + 1
            // dispatch_group_enter 和 dispatch_group_leave 是成对出现的
            dispatch_group_enter(group);
           [[SDWebImageManager sharedManager] downloadImageWithURL:s.pictureURLs[0] options:SDWebImageLowPriority  progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
               dispatch_group_leave(group);
               NSLog(@"下载完成了,当前的线程为  %@",[NSThread currentThread]);
           }];
        }
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog("原创微博的单张图片下载完成");
        isSuccess(true);
    });
}


@end
